package com.lzj.jiangxindaojia.view.login.ali;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;

/**
 * Created by frank on 16/12/19.
 * Modified by alan on 17/11/08
 */

public class IFAAFingerprintOpenAPI {
    public  static final String TAG = "IFAAFingerprintOpenAPI";
    public static final boolean checkFingerId = true;

    /*** ATTENTION!!!: YOU SHOULD NOT INVOLVE THIS PART OF CODE INTO YOUR APPLICATION/CLIENT CODE ***/
    /***************** This file of code is only to emulate the behavior of biz server. *************/

    /*
     * Openapi is a net gate for Ant Financial's open services. The private
     * and public key are only test keys to let you try this service. In your
     * server side, you should use your own private key and alipay openapi's public key
     * */
    private String priKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDeI+gMtH7Vrhb4WO9Mc3AkQzgKBVTGHqUi6SrWonr4/391iFp6AXONqlTLj2TRiklkPnKC5VAgBwdHbo1ab/Kd/cmwia2DQuQ0fchOBQIzrMfe6HMAoRkDqLCKfiuF24K4H8yi2s2tYn0zqxmclH88Gfs/vSkgVe4oogTt+MJ9wfk2pj2nI6p4YrL+ERlUTmZqHKNVTRp1j+pzctsOwRyI69ndVJ1Tecw47gfNATGy56X7Kdajre/27+ERa1J0lXiXFRBobEo4vLMEI4GBLG7enSFLDX8vHbtRQ6B+Dez6D/N/lqWtwIcTky3Uk76WrX8jg0/aGEKj+I3++rmPg7WzAgMBAAECggEBANBGDh1LZdfmX7b9e2/MlAoL1BDhKriOpvnyb63JrU6kDtcdvubBUZwzZUlt6nLkGyeXvTmo0tUUgeihaHqwl2M2PdH9Y+e74catYA52d7gHeWYvvxOJ97AMi2luHlRkmU0U04Klb03vF8BH3b2HJTwuh/kc2+BrcN47+i88mu3YHtDoJrMm/ePyyEmFu9PBkGi67nWSmpCm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gKCAQEAxFesOw1cbp4DcDIURqlc96cUfFlOZBxyiVk/Q7GXi/WtyLDJjO0IxQtxJpI+2Lt0+/P+l3g5u8WdUGcUnGGO2O98QLOFnvPRVmmDVVOy6j5vsBqqB8+iILrHOeePbeuBTQnzpIrrmbbV2QxJ9UJUke6DyYbmAoyKld4dypTk8eg2Nont22dKU5IIGkDo0UIQuhB4YRj3VTemwS5NX+2rAIRQ3kLKqC2Ug3L4nYORiWqKgJaZJGtjil7pLMtOhn/eH00iUAXadk9iqH9c4NtGOVJClrD93IvTDh+EGoZG7xrOagtyikb65c8wQjIJVjfGJdypEQWRVZihOuRU4ilNqQIDAQAB";


    /* APPID is the unique identity of applications on Openapi platform
     * This appid is only for test.
     * */
    private String aid = "2016082000295404";

    /* This is the URL of Openapi platform */
    private String url = "https://openapi.alipaydev.com/gateway.do";


    AlipayClient alipayClient = null;
    String token = null;


    public interface Callback {
       void onCompeleted(int status, String info);
    }

    private static IFAAFingerprintOpenAPI instance;
    public static IFAAFingerprintOpenAPI getInstance() {
        if (instance == null) {
            instance = new IFAAFingerprintOpenAPI();
        }
        return instance;
    }
    public IFAAFingerprintOpenAPI() {
         alipayClient = new DefaultAlipayClient(url,aid,priKey,"json","GBK",aliPubKey, "RSA2");
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
    public void getRegRequestAsyn(final String secData, final Callback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                IFAAFingerprintOpenAPI.this.getRegRequest(secData, callback);
            }
        }).start();
    }

    public void getAuthRequestAsyn(final String secData, final Callback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                IFAAFingerprintOpenAPI.this.getAuthRequest(secData, callback);
            }
        }).start();
    }

    public void sendRegResponeAsyn(final String regResponse,final String secData, final Callback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                IFAAFingerprintOpenAPI.this.sendRegResponse(regResponse, secData, callback);
            }
        }).start();
    }

    public void sendAuthResponeAsyn(final String regResponse,final String secData, final Callback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                IFAAFingerprintOpenAPI.this.sendAuthResponse(regResponse, secData, callback);
            }
        }).start();
    }

    public void sendAuthUpdateMultiFingersResponeAsyn(final String regResponse,final String secData, final Callback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                IFAAFingerprintOpenAPI.this.sendAuthUpdateMultiFingersResponse(regResponse, secData, callback);
            }
        }).start();
    }

    public void getDeregRequestAsyn(final String secData, final Callback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                IFAAFingerprintOpenAPI.this.getDeregRequest(secData, callback);
            }
        }).start();
    }

    public class AlipaySecurityProdFingerprintApplyInitializeRequest extends AlipayTradePayRequest {

        public String getApiMethodName() {
            return "alipay.security.prod.fingerprint.apply.initialize";
        }

    }

    public class AlipaySecurityProdFingerprintApplyRequest extends AlipayTradePayRequest {

        public String getApiMethodName() {
            return "alipay.security.prod.fingerprint.apply";
        }

    }

    public class AlipaySecurityProdFingerprintVerifyInitializeRequest extends AlipayTradePayRequest {

        public String getApiMethodName() {
            return "alipay.security.prod.fingerprint.verify.initialize";
        }

    }

    public class AlipaySecurityProdFingerprintVerifyRequest extends AlipayTradePayRequest {

        public String getApiMethodName() {
            return "alipay.security.prod.fingerprint.verify";
        }

    }

    public class AlipaySecurityProdFingerprintDeleteRequest extends AlipayTradePayRequest {

        public String getApiMethodName() {
            return "alipay.security.prod.fingerprint.delete";
        }

    }


    private void getRegRequest(String secData, Callback callback) {
        AlipaySecurityProdFingerprintApplyInitializeRequest request = new AlipaySecurityProdFingerprintApplyInitializeRequest();
        secData = secData.replace("\"", "\\\"");
        String bizContent = "{" +
                "    \"auth_type\":\"1\"," +
                "    \"ifaa_version\":\"2.0\"," +
                "    \"sec_data\": \"" + secData + "\"" +
                "  }";
        Log.i(TAG , "bizcontent:" + bizContent);
        request.setBizContent(bizContent);
        AlipayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response != null && response.isSuccess()){
            System.out.println("Success");
            Log.i(TAG, "register resp body:" + response.getBody());
            JSONObject jo = JSON.parseObject(response.getBody());
            JSONObject resp = jo.getJSONObject("alipay_security_prod_fingerprint_apply_initialize_response");
            if (resp != null) {
                if (callback != null) {
                    callback.onCompeleted(0, resp.getString("server_response"));
                }
            }
        } else {
            System.out.println("Fail");
        }

    }


    private void getAuthRequest(String secData, Callback callback) {
        AlipaySecurityProdFingerprintVerifyInitializeRequest request = new AlipaySecurityProdFingerprintVerifyInitializeRequest();
        secData = secData.replace("\"", "\\\"");
        String bizContent = "{" +
                "    \"token\":\"" + token + "\"," +
                "    \"ifaa_version\":\"2.0\"," +
                "    \"sec_data\": \"" + secData + "\"" +
                "  }";
        Log.i(TAG , "bizcontent:" + bizContent);
        request.setBizContent(bizContent);
        AlipayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response != null && response.isSuccess()){
            System.out.println("Success");
            Log.i(TAG, "verify init resp body:" + response.getBody());
            JSONObject jo = JSON.parseObject(response.getBody());
            JSONObject resp = jo.getJSONObject("alipay_security_prod_fingerprint_verify_initialize_response");
            if (resp != null) {
                if (callback != null) {
                    callback.onCompeleted(0, resp.getString("server_response"));
                }
            }
        } else {
            System.out.println("Fail");
        }

    }

    private void sendRegResponse(String regResponse, String secData, Callback callback) {
        AlipaySecurityProdFingerprintApplyRequest request = new AlipaySecurityProdFingerprintApplyRequest();
        secData = secData.replace("\"", "\\\"");
        regResponse = regResponse.replace("\"", "\\\"");
        String bizContent = "{" +
                "    \"out_biz_no\":\"20161126200040011100190086557102\"," +
                "    \"ifaa_version\":\"2.0\"," +
                "    \"sec_data\": \"" + secData + "\"," +
                "    \"ifaf_message\": \"" + regResponse + "\"" +
                "  }";
        Log.i(TAG , "bizcontent:" + bizContent);
        request.setBizContent(bizContent);
        AlipayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response != null && response.isSuccess()){
            System.out.println("Success");
            Log.i(TAG, "register resp body:" + response.getBody());
            JSONObject jo = JSON.parseObject(response.getBody());
            JSONObject resp = jo.getJSONObject("alipay_security_prod_fingerprint_apply_response");
            if (resp != null) {
                token = resp.getString("token");
                if (callback != null) {
                    callback.onCompeleted(resp.getString("msg").equalsIgnoreCase("Success") ? 0 : -1, resp.getString("sub_code"));
                }
            }
        } else {
            System.out.println("Fail");
        }

    }


    private void sendAuthResponse(String verifyResponse, String secData, Callback callback) {
        secData = secData.replace("\"", "\\\"");
        verifyResponse = verifyResponse.replace("\"", "\\\"");
        AlipaySecurityProdFingerprintVerifyRequest request = new AlipaySecurityProdFingerprintVerifyRequest();
        String bizContent;
        if (checkFingerId) {
          bizContent = "{" +
                "    \"out_biz_no\":\"20161126200040011100190086557102\"," +
                "    \"ifaa_version\":\"2.0\"," +
                "    \"sec_data\": \"" + secData + "\"," +
                "    \"ifaf_message\": \"" + verifyResponse + "\"," +
                "    \"extend_param\": {\"needAuthData\" : true, \"subAction\" : \"authenticate\"}"+
                "  }";
        } else {
          bizContent = "{" +
                "    \"out_biz_no\":\"20161126200040011100190086557102\"," +
                "    \"ifaa_version\":\"2.0\"," +
                "    \"sec_data\": \"" + secData + "\"," +
                "    \"ifaf_message\": \"" + verifyResponse + "\"" +
                "  }";

        }
        Log.i(TAG , "bizcontent:" + bizContent);
        request.setBizContent(bizContent);
        AlipayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response != null && response.isSuccess()){
            System.out.println("Success");
            Log.i(TAG, "verify resp body:" + response.getBody());
            JSONObject jo = JSON.parseObject(response.getBody());
            JSONObject resp = jo.getJSONObject("alipay_security_prod_fingerprint_verify_response");
            if (resp != null) {
                if (callback != null) {
                    callback.onCompeleted(resp.getString("msg").equalsIgnoreCase("Success") ? 0 : -1, resp.getString("sub_code"));
                }
            }
        } else {
            System.out.println("Fail");
        }

    }

    private void sendAuthUpdateMultiFingersResponse(String verifyResponse, String secData, Callback callback) {
        secData = secData.replace("\"", "\\\"");
        verifyResponse = verifyResponse.replace("\"", "\\\"");
        AlipaySecurityProdFingerprintVerifyRequest request = new AlipaySecurityProdFingerprintVerifyRequest();
        String bizContent;
        if (checkFingerId) {
            bizContent = "{" +
                    "    \"out_biz_no\":\"20161126200040011100190086557102\"," +
                    "    \"ifaa_version\":\"2.0\"," +
                    "    \"sec_data\": \"" + secData + "\"," +
                    "    \"ifaf_message\": \"" + verifyResponse + "\"," +
                    "    \"extend_param\": {\"needAuthData\" : true, \"subAction\" : \"update\"}"+
                    "  }";
        } else {
            bizContent = "{" +
                    "    \"out_biz_no\":\"20161126200040011100190086557102\"," +
                    "    \"ifaa_version\":\"2.0\"," +
                    "    \"sec_data\": \"" + secData + "\"," +
                    "    \"ifaf_message\": \"" + verifyResponse + "\"" +
                    "  }";

        }
        Log.i(TAG , "bizcontent:" + bizContent);
        request.setBizContent(bizContent);
        AlipayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response != null && response.isSuccess()){
            System.out.println("Success");
            Log.i(TAG, "verify resp body:" + response.getBody());
            JSONObject jo = JSON.parseObject(response.getBody());
            JSONObject resp = jo.getJSONObject("alipay_security_prod_fingerprint_verify_response");
            if (resp != null) {
                if (callback != null) {
                    callback.onCompeleted(resp.getString("msg").equalsIgnoreCase("Success") ? 0 : -1, resp.getString("sub_code"));
                }
            }
        } else {
            System.out.println("Fail");
        }

    }
    private void getDeregRequest(String secData, Callback callback) {
        secData = secData.replace("\"", "\\\"");
        AlipaySecurityProdFingerprintDeleteRequest request = new AlipaySecurityProdFingerprintDeleteRequest();
        String bizContent = "{" +
                "    \"token\":\"" + token + "\"," +
                "    \"ifaa_version\":\"2.0\"," +
                "    \"sec_data\": \"" + secData + "\"" +
                "  }";
        Log.i(TAG , "bizcontent:" + bizContent);
        request.setBizContent(bizContent);
        AlipayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response != null && response.isSuccess()){
            System.out.println("Success");
            Log.i(TAG, "verify resp body:" + response.getBody());
            JSONObject jo = JSON.parseObject(response.getBody());
            JSONObject resp = jo.getJSONObject("alipay_security_prod_fingerprint_delete_response");
            if (resp != null) {
                if (callback != null) {
                    callback.onCompeleted(0, resp.getString("server_response"));
                }
            }
        } else {
            System.out.println("Fail");
        }

    }
}
